package com.neu.controller;

import com.neu.base.PageBean;
import com.neu.base.Result;
import com.neu.entity.*;
import com.neu.entity.DTO.ReviewReportDTO;
import com.neu.service.*;
import com.neu.service.impl.TenantServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.minio.messages.Progress;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/display")
@Tag(name = "数据展示")
public class DisplayController {
    @Autowired
    private TaskService taskService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskUserService taskUserService;
    @Autowired
    private TenantServiceImpl tenantServiceImpl;
    @Autowired
    private ReportInfoService reportInfoService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ProgressRecordService progressRecordService;

    @PostMapping("/getMonthlyWorkload")
    @Parameters(
            @Parameter(name = "userid", description = "租户的id", required = true)
    )
    @Operation(summary = "获取逐月工作进度")
    public Result getMonthlyWorkload(@RequestParam String userid) {
        // 返回上周-上月+4的逐月完成与总工作量
        List<Project> projectList = projectService.list();
        List<Task> taskList = taskService.list();
        List<Task> selectTaskList = new ArrayList<>();
        for (Project project : projectList) {
            if (project.getTenantId().equals(userid)){
                for (Task task : taskList) {
                    if(task.getProjectId().equals(project.getProjectId())){
                        selectTaskList.add(task);
                    }
                }
            }
        }

        LocalDate today = LocalDate.now();
        LocalDate sevenDaysAgo = today.minusDays(7);
        LocalDate fourteenDaysLater = today.plusDays(14);

        // 创建一个包含从7天前到14天后每天日期的列表
        List<LocalDate> dateRange = new ArrayList<>();
        for (LocalDate date = sevenDaysAgo; !date.isAfter(fourteenDaysLater); date = date.plusDays(1)) {
            dateRange.add(date);
        }

        // 初始化统计结果列表
        List<Map<String, String>> statsList = new ArrayList<>();

        // 对每个日期进行统计
        for (LocalDate date : dateRange) {
            int status1Count = 0;
            int totalCount = 0;

            // 过滤出当前日期的任务并统计状态
            for (Task task : selectTaskList) {
                if (task.getDueDate().toLocalDate().equals(date)) {
                    totalCount++;
                    if (task.getTaskStatus().equals("2")) {
                        status1Count++;
                    }
                }
            }

            // 将统计结果放入Map并添加到列表中
            Map<String, String> stats = new HashMap<>();
            stats.put("date", date.toString());
            stats.put("finishWorkCount", Integer.toString(status1Count));
            stats.put("dueWorkCount", Integer.toString(totalCount));
            statsList.add(stats);
        }

        // 返回统计结果
        return Result.success(statsList);
    }

    @PostMapping("/basicInformation")
    @Parameters(
            @Parameter(name = "userid", description = "租户的id", required = true)
    )
    @Operation(summary = "获取该租户所有项目的基本信息")
    public Result basicInformation(@RequestParam String userid) {
        List<Project> projectList = projectService.list();
        List<Project> selectProjectList = new ArrayList<>();
        for (Project project : projectList) {
            if (project.getTenantId().equals(userid)){
                selectProjectList.add(project);
            }
        }
        List<Task> taskList = taskService.list();
        List<Task> selectTaskList = new ArrayList<>();
        for (Project project : projectList) {
            if (project.getTenantId().equals(userid)){
                for (Task task : taskList) {
                    if(task.getProjectId().equals(project.getProjectId())){
                        selectTaskList.add(task);
                    }
                }
            }
        }

        List<TaskUser> taskUserList = taskUserService.list();

        List<User> selectUserList = userService.findUserByTenantId(userid);

        Map<String, Object> result = new HashMap<>();

        int totalTaskNum = selectTaskList.size();
        int status2Count = 0;
        for (Task task : selectTaskList) {
            if (task.getTaskStatus().equals("2")) {
                status2Count++;
            }
        }


        result.put("totalTaskProgress", status2Count / (float)totalTaskNum * 100);
        result.put("totalTaskNum", totalTaskNum);

        int totalProjectNum = selectProjectList.size();
        status2Count = 0;


        for (Project project : selectProjectList) {

            if (project.getProjectStatus().equals("2")) {
                status2Count++;
            }
        }


        result.put("totalProjectProgress", status2Count / (float)totalProjectNum * 100);
        result.put("totalProjectNum", totalProjectNum);

        LocalDate today = LocalDate.now();
        long minDays = 100000;
        Project latestProject = null;
        for (Project project : selectProjectList) {
            if (minDays > ChronoUnit.DAYS.between(today, project.getDueDate().toLocalDate()) && !project.getProjectStatus().equals("2")) {
                latestProject = project;
                minDays = ChronoUnit.DAYS.between(today, project.getDueDate().toLocalDate());
            }
        }


        result.put("leftDaysOfLatestProject", minDays);
        result.put("latestProject", latestProject);

        float tmpNum = 0;
        for (User user : selectUserList) {
            for (TaskUser taskUser : taskUserList) {
                if (taskUser.getUserId().equals(user.getUserId())) {
                    Task task = taskService.getById(taskUser.getTaskId());
                    if (!task.getTaskStatus().equals("2")) {
                        tmpNum++;
                    }
                }
            }
        }


        result.put("StaffUtilization", tmpNum / selectUserList.size() / 3 * 100);

        return Result.success(result);
    }

    @PostMapping("/staffDeploy")
    @Parameters(
            @Parameter(name = "userid", description = "租户的id", required = true)
    )
    @Operation(summary = "获取员工的分配信息用于绘制柱状图")
    public Result staffDeploy(@RequestParam String userid) {
        List<User> userList = userService.findUserByTenantId(userid);
        List<Task> taskList = taskService.list();

        LocalDate today = LocalDate.now();
        LocalDate threeDaysAgo = today.minusDays(3);
        LocalDate threeDaysLater = today.plusDays(3);

        List<Map<String, String>> statsList = new ArrayList<>();
        List<LocalDate> dateRange = new ArrayList<>();
        for (LocalDate date = threeDaysAgo; !date.isAfter(threeDaysLater); date = date.plusDays(1)) {
            dateRange.add(date);
        }

        for (LocalDate date : dateRange){
            int workStaff = 0;
            for (User user : userList) {
                for (Task task : taskList) {
                    if (task.getAssignedTo().equals(user.getUserId()) && (date.isBefore(task.getDueDate().toLocalDate()) || date.isEqual(task.getDueDate().toLocalDate()))
                    && (date.isAfter(task.getCreateTime().toLocalDate()) || date.isEqual(task.getCreateTime().toLocalDate()))) {
                        workStaff++;
                        break;
                    }
                }
            }

            Map<String, String> result = new HashMap<>();
            result.put("date", date.toString());
            result.put("workStaff", Integer.toString(workStaff));
            statsList.add(result);
        }

        return Result.success(statsList);
    }

    @PostMapping("/taskDiagram")
    @Parameters(
            @Parameter(name = "userid", description = "租户的id", required = true)
    )
    @Operation(summary = "获取任务视图所需任务")
    public Result taskDiagram(@RequestParam String userid) {
        List<Project> projectList = projectService.list();
        List<Project> selectProjectList = new ArrayList<>();
        for (Project project : projectList) {
            if (project.getTenantId().equals(userid)){
                selectProjectList.add(project);
            }
        }
        List<Task> taskList = taskService.list();
        List<Task> selectTaskList = new ArrayList<>();
        for (Project project : projectList) {
            if (project.getTenantId().equals(userid)){
                for (Task task : taskList) {
                    if(task.getProjectId().equals(project.getProjectId())){
                        selectTaskList.add(task);
                    }
                }
            }
        }

        List<Task> fpTaskList = new ArrayList<>();
        List<Task> costTaskList = new ArrayList<>();
        List<Task> reviewTaskList = new ArrayList<>();
        for (Task task : selectTaskList) {
            if (task.getTaskType().equals("3")) {
                reviewTaskList.add(task);
            }else if (task.getTaskType().equals("2")) {
                costTaskList.add(task);
            }else{
                fpTaskList.add(task);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("functionAnalysisTasks", fpTaskList);
        result.put("costTasks", costTaskList);
        result.put("reviewTasks", reviewTaskList);

        return Result.success(result);
    }

    @PostMapping("/getTask")
    @Parameters(
            @Parameter(name = "taskid", description = "任务的id", required = true)
    )
    @Operation(summary = "获取任务具体信息")
    public Result getTask(@RequestParam String taskid) {
        Task task = taskService.getById(taskid);
        Project project = projectService.getById(task.getProjectId());
        Tenant tenant = tenantServiceImpl.getById(project.getTenantId());
        User worker = userService.getById(task.getAssignedTo());

        Map<String, Object> result = new HashMap<>();
        result.put("task", task);
        result.put("project", project);
        result.put("tenant", tenant.getTenantName());
        result.put("worker", worker.getNickname());

        return Result.success(result);
    }

    @PostMapping("/getProjects")
    @Parameters(
            @Parameter(name = "tenantid", description = "租户的id", required = true)
    )
    @Operation(summary = "获取该租户所有的项目及其信息")
    public Result getProjects(@RequestParam String tenantid) {
        List<Project> projectList = projectService.list();
        List<Project> selectProjectList = new ArrayList<>();
        for (Project project : projectList) {
            if (project.getTenantId().equals(tenantid)) {
                selectProjectList.add(project);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("projects", selectProjectList);
        List<String> reviewStatusList = new ArrayList<>();
        List<Task> selectTaskList = new ArrayList<>();
        for(Project project : selectProjectList){
            for (Task task : taskService.list()) {
                if (task.getProjectId().equals(project.getProjectId())) {
                    selectTaskList.add(task);
                }
            }
        }
        for (Project project : selectProjectList) {
            if (project.getProjectStatus().equals("2")) {
                reviewStatusList.add("已完成");

                continue;
            }

            if (project.getProjectStatus().equals("0")) {
                reviewStatusList.add("未开始");

                continue;
            }

            boolean flag = false;

            for (Task task : selectTaskList) {
                if (task.getProjectId().equals(project.getProjectId()) && task.getTaskType().equals("2") && task.getTaskStatus().equals("2")) {
                    boolean tmpFlag = false;
                    for(Task task2 : selectTaskList){
                        if(task2.getTaskType().equals("3") && task2.getProjectId().equals(project.getProjectId())){
                            reviewStatusList.add("评审中");
                            tmpFlag = true;
                        }
                    }

                    if (!tmpFlag){
                        reviewStatusList.add("评估完成");
                    }

                    flag = true;
                    break;
                }
            }

            if (flag){
                continue;
            }else {
                reviewStatusList.add("评估中");
            }
        }

        result.put("projectStatus", reviewStatusList);

        List<Double> progressList = new ArrayList<>();
        for (Project project : selectProjectList) {
            double progress = 0;
            for (Task task : taskService.list()) {
                if (task.getProjectId().equals(project.getProjectId())) {
                    progress += task.getProgress();
                }
            }

            progressList.add(progress / 3);
        }

        result.put("progress", progressList);

        return Result.success(result);
    }

    @PostMapping("/getFinishedProjects")
    @Parameters(
            @Parameter(name = "tenantid", description = "租户的id", required = true)
    )
    @Operation(summary = "获取该租户所有的完成项目")
    public Result getFinishedProjects(@RequestParam String tenantid) {
        List<Project> projectList = projectService.list();
        List<Project> selectProjectList = new ArrayList<>();
        List<String> tenantNames = new ArrayList<>();
        for (Project project : projectList) {
            if (project.getTenantId().equals(tenantid) && project.getProjectStatus().equals("2")) {
                selectProjectList.add(project);

                String tenantName = tenantServiceImpl.getById(project.getTenantId()).getTenantName();
                tenantNames.add(tenantName);
            }
        }



        Map<String, Object> result = new HashMap<>();
        result.put("projects", selectProjectList);
        result.put("tenantNames", tenantNames);

        return Result.success(result);
    }

    @PostMapping("/getReportInfo")
    @Parameters(
            @Parameter(name = "projectId", description = "完成项目的id", required = true)
    )
    @Operation(summary = "获取该项目的报告信息")
    public Result getReportInfo(@RequestParam String projectId) {
        return Result.success(reportInfoService.getByProjectId(projectId));
    }

    @PostMapping("/getAIAnswer")
    @Parameters({
            @Parameter(name = "aiId", description = "ai_id", required = true),
            @Parameter(name = "question", description = "问题文本", required = true)
    })
    @Operation(summary = "获取报告的AI回答")
    public Result getAIAnswer(HttpServletRequest request, @RequestParam String aiId, @RequestParam String question){
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("aiId", aiId);
        requestBody.put("question", question);

        String flaskUrl = "http://localhost:5000/talk";
        String token = request.getHeader("Authorization");
        requestBody.put("token", token);

        ResponseEntity<Result> response = restTemplate.postForEntity(flaskUrl, requestBody, Result.class);

        return Result.success(response.getBody());
    }

    @PostMapping("/search")
    @Operation(summary = "搜索项目报告")
    public Result search(
            @RequestBody Map map){
        Map<String, Object> result = reportInfoService.search(map);
        return Result.success(result);
    }

    @PostMapping("/getTaskStastic")
    @Operation(summary = "获取任务统计数据")
    @Parameters(
            @Parameter(name="taskid", description = "任务的id", required = true)
    )
    public Result getTaskStastic(@RequestParam String taskid){
        List<ProgressRecord> recordList = progressRecordService.list();
        List<ProgressRecord> selectRecordList = new ArrayList<>();
        for (ProgressRecord record : recordList) {
            if (record.getTaskId().equals(taskid)) {
                selectRecordList.add(record);
            }
        }
        int recordProgress = 0;

        List<Integer> progressList = new ArrayList<>();
        for (int i = 3; i >=0; i--) {
            LocalDate date = LocalDate.now().minusDays(i);
            for (ProgressRecord record : selectRecordList) {
                if(record.getRecordTime().toLocalDate().isEqual(date)){
                    if(record.getProgress() > recordProgress){
                        recordProgress = record.getProgress();
                    }
                }
            }

            progressList.add(recordProgress);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("progressList", progressList);

        List<Double> averageList = new ArrayList<>();
        for (int i = 3; i >=0; i--) {
            LocalDate date = LocalDate.now().minusDays(i);
            double total = 0;
            double count = 0;
            for (ProgressRecord record : recordList) {
                if (record.getRecordTime().toLocalDate().isEqual(date)){
                    count += 1;
                    total += (double)record.getProgress();
                }


            }
            if (count == 0){
                averageList.add(count);
            }else {
                averageList.add(total / count);
            }
        }

        result.put("averageList", averageList);

        return Result.success(result);
    }

}
